package org.ithang.tools.eth;

import java.net.URI;

import org.apache.log4j.Logger;
import org.ithang.application.bcAddr.bean.BcAddr;
import org.ithang.application.bcAddr.service.BcAddrService;
import org.ithang.application.bcRecord.service.BcRecordService;
import org.ithang.application.btAddr.bean.BtAddr;
import org.ithang.application.btAddr.service.BtAddrService;
import org.ithang.application.btRecord.bean.BtRecord;
import org.ithang.application.btRecord.service.BtRecordService;
import org.ithang.system.keyvalue.bean.Keyvalue;
import org.ithang.system.keyvalue.service.KeyvalueService;
import org.ithang.tools.lang.JsonUtils;
import org.ithang.tools.lang.StrUtils;
import org.ithang.tools.model.ErrorInfo;
import org.ithang.tools.redis.Keys;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

public class ETHWebSocket extends WebSocketClient {

	private static URI uri=null;
	
	private BcAddrService bcAddrService;
	
	private BtAddrService btAddrService;
	
	private BtRecordService btRecordService;
	
	private BcRecordService bcRecordService; 
	
	private KeyvalueService keyvalueService;
	
	private boolean close=false;
	
	private static Logger logger = Logger.getLogger(ETHWebSocket.class);
	
	static{
		try{
			uri=new URI("ws://23.234.3.127:7579/ws");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	public ETHWebSocket() {
		this(uri);
	}
	
	public ETHWebSocket(URI serverUri) {
		super(serverUri);
	}

	@Override
	public void onClose(int arg0, String arg1, boolean arg2) {
		logger.warn("websocket close");
		close=true;
	}

	@Override
	public void onError(Exception e) {
		e.printStackTrace();
		logger.error(e.getMessage());
	}

	@Override
	public void onMessage(String data) {
		close=false;
		//System.out.println("接收到信息:"+data);
        if(StrUtils.isNotBlank(data)&&data.indexOf("data")>-1){
        	logger.info("接收到交易信息:"+data);
        	System.out.println("处理交易信息:"+data);
        	ETHInfo ei=JsonUtils.parseJson(data, ETHInfo.class);
        	
        	if(null!=ei&&200==ei.getStatus()){
        		
        		boolean recharge=false;//充
        		boolean withdraw=false;//提
        		String from=ei.getData().get("from");//发送地址
        		String to=ei.getData().get("to");//接收地址
        		String value=ei.getData().get("value");//转账金额
        		String blockHash=ei.getData().get("blockHash");//区块hash值
        		String status=ei.getData().get("status");
        		
        		BtAddr btAddr=null;
        		BcAddr bcaddr=bcAddrService.getByAddr(to);
        		if(null!=bcaddr){//证明用户充值了
        			recharge=true;
        		}else{
        			btAddr=btAddrService.getByAddr(to);
        			if(null!=btAddr&&from.equals(ETHUtil.TestTokenAddress)){
        				withdraw=true;
        			}
        		}
        		
        		if(!withdraw&&!recharge){
        			logger.error("不是有效数据："+JsonUtils.toJsonStr(ei));
        			return;
        		}
        		
        		
        		
        		//失败结果处理start===========================================
                if("0".equals(status)){//失败
        			if(withdraw){//提
        				BtRecord btr=btRecordService.getByTXHash(blockHash);
        				if(null!=btr){
        					btr.setResult(5);
        					btRecordService.withdrawFail(btr);
        				}
        			}
        			if(recharge){//充
        				//充值失败处理
        				bcRecordService.rechargeFail(JsonUtils.toJsonStr(ei), value,bcaddr.getCustomer_id(),blockHash);
        			}
        		}
                //失败结果处理end===========================================
                
                
              //挖矿结果处理start===========================================
                if("2".equals(status)){//挖矿中
                    if(withdraw){//提
                    	BtRecord btr=btRecordService.getByTXHash(blockHash);
        				if(null!=btr){
        					BtRecord bt=new BtRecord();
        					bt.setId(btr.getId());
        					bt.setResult(4);
        					btRecordService.update(bt);
        				}
        			}
        			if(recharge){//充
        				//不做处理
        			}
        		}
              //挖矿成功结果处理start===========================================
                
                
              //成功结果处理start===========================================
                if("1".equals(status)){//成功
                    if(withdraw){//提
                    	BtRecord btr=btRecordService.getByTXHash(blockHash);
        				if(null!=btr){
        					btr.setResult(6);
        					btRecordService.withdrawSuccess(btr);
        				}
        			}
        			if(recharge){//充
        				
        				Keyvalue kv=keyvalueService.get(Keys.MinRecharge);
        				if(Double.parseDouble(value)<kv.doubleValue()){
        					
        				}else{
        					bcRecordService.rechargeSuccess(JsonUtils.toJsonStr(ei), value,bcaddr.getCustomer_id(),blockHash);	
        				}
        			}
        		}
              //成功结果处理end===========================================
        	}
        	
        }
	}

	@Override
	public void onOpen(ServerHandshake sh) {
		send("{sub:\"eth_usdt\"}");
	}

	public BcAddrService getBcAddrService() {
		return bcAddrService;
	}

	public void setBcAddrService(BcAddrService bcAddrService) {
		this.bcAddrService = bcAddrService;
	}

	public BtAddrService getBtAddrService() {
		return btAddrService;
	}

	public void setBtAddrService(BtAddrService btAddrService) {
		this.btAddrService = btAddrService;
	}

	public BtRecordService getBtRecordService() {
		return btRecordService;
	}

	public void setBtRecordService(BtRecordService btRecordService) {
		this.btRecordService = btRecordService;
	}

	public BcRecordService getBcRecordService() {
		return bcRecordService;
	}

	public void setBcRecordService(BcRecordService bcRecordService) {
		this.bcRecordService = bcRecordService;
	}

	public boolean isClose() {
		return close;
	}

	public void setClose(boolean close) {
		this.close = close;
	}

	public KeyvalueService getKeyvalueService() {
		return keyvalueService;
	}

	public void setKeyvalueService(KeyvalueService keyvalueService) {
		this.keyvalueService = keyvalueService;
	}
	
	
	
}
